package chances.epg.data.taglib;

import java.util.List;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.data.taglib.page.PageInfo;
import chances.epg.entity.biz.Biz;
import chances.epg.navigator.context.AccessContextUtils;


/**
 * 子展示栏目.
 * 支持分页查询.
 * @author Elysium
 *
 */
public class BizListTag extends QueryListTag {
	private static final Logger logger = EpgLogFactory.getSystemLogger();
	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = -6521360420936020498L;
	private String code;
	private int size;

	@Override
	public int doEndTag() throws JspException {
		String bizCode = this.getCode();
		if(StringUtils.isBlank(bizCode)){
			bizCode = this.getCurBizCode();
		}
		
		if(StringUtils.isBlank(bizCode)){
			logger.debug("bizCode and curBizCode is null.");
		}
		
		try{
			if(StringUtils.isNotBlank(this.getPageName())){
				this.queryBizListByPage(bizCode);
			}else{
				this.queryBizList(bizCode);
			}
		}catch(Throwable ex){
			logger.error("BizListTag error.",ex);
		}
		
		return super.doEndTag();
	}
	
	private void queryBizList(String bizCode) {
		List<Biz> result = this.getBizService().getChildrenOfBiz(bizCode);
		if(size > 0 && size < result.size()) {
			this.setBizList(result.subList(this.start, size));
		}else{
			this.setBizList(result);
		}
	}
	
	private void queryBizListByPage(String bizCode) {
		PageInfo pageInfo = this.createPageInfo(size);
		List<Biz> result = this.getBizService().getChildrenOfBiz(bizCode, 0, pageInfo.getPageBean());
		this.setPageInfo(pageInfo);
		this.setBizList(result);
		this.pageNo = 0;
	}
	
	/**
	 * 
	 * @param result
	 */
	private void setBizList(List<Biz> result) {
		for (Biz biz : result) {
			biz.setUrl(navigateUrlFactory.generateURL(AccessContextUtils.getAccessContext(pageContext), biz));
		}
		this.setCollectionResult(result);
	}
	
	
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
}
